package com.py.credit.service.impl;

import com.py.credit.common.Page;
import com.py.credit.common.ServiceException;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.dao.GzDao;
import com.py.credit.entity.GzObj;
import com.py.credit.service.GzService;
import com.py.credit.utils.FileUtil;
import com.py.credit.utils.SQLBuilder;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class GzServiceImpl implements GzService {

    @Autowired
    private GzDao gzDao;

    @Override
    public List<Map<String, Object>> getByConditionForPage(String type, List<String> showColumns, String[] additionalColumns, String condition, Page page) {
        if (CollectionUtils.isEmpty(showColumns)) {
            throw new ServiceException("至少选择一列");
        }
        List<String> conditions = SQLBuilder.createConditionSql(condition);

        return gzDao.selectByConditionForPage(type, showColumns, additionalColumns, conditions, page);
    }

    @Override
    public List<Map<String, Object>> selectForLhbm(int id) {
        // TODO Auto-generated method stub
        return gzDao.selectForLhbm(id, null, null);
    }

    @Override
    public void add(MultipartFile file, String name, String bm, String detailName, String cfbm,
                    String csIds, String bmIds, String lyIds, String type, String absolutepath) {
        // TODO Auto-generated method stub
        // 文件存储路径
        String path = "";
        if (null != file) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String date = sdf.format(new Date());
            String dest = absolutepath + File.separator + "gzUpload" + File.separator + date + File.separator;
            path = dest + file.getOriginalFilename();

            try {
                saveFile(file.getBytes(), path);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        List<String> bms = Arrays.asList(bmIds.split(","));
        List<String> css = Arrays.asList(csIds.split(","));
        List<String> lys = Arrays.asList(lyIds.split(","));

        GzObj gzObj = new GzObj();
        gzObj.setFilePath(path);
        gzObj.setName(name);
        gzObj.setBm(bm);
        gzObj.setDetailName(detailName);
        gzObj.setCfbm(cfbm);
        gzObj.setJclb(type);
        gzDao.add(gzObj);
        int gzId = gzObj.getId();

        for (int i = 0; i < bms.size(); i++) {
            gzDao.insertGzAndCs(gzId + "", css.get(i), bms.get(i), lys.get(i).equals("undefined") ? "0" : lys.get(i));
        }
    }

    /***
     * 保存文件
     *
     * @param file
     * @param dest
     *            路径
     * @return
     */
    private void saveFile(byte[] file, String dest) {
        try {
            FileUtils.copyInputStreamToFile(new ByteArrayInputStream(file), new File(dest));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int selectSameBmAndName(String name, String bm) {
        return gzDao.selectSameBmAndName(name, bm);
    }

    @Override
    public GzObj selectById(String id) {
        return gzDao.selectById(id);
    }

    @Override
    public void modifyById(String id, MultipartFile file, String name, String bm, String detailName, String cfbm,
                           String csIds, String bmIds, String lyIds, String absolutepath) {
        String filePath = "";
        if (null != file) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String date = sdf.format(new Date());
            String dest = absolutepath + File.separator + "gzUpload" + File.separator + date + File.separator;
            filePath = dest + file.getOriginalFilename();

            try {
                saveFile(file.getBytes(), filePath);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        List<String> bms = Arrays.asList(bmIds.split(","));
        List<String> css = Arrays.asList(csIds.split(","));
        List<String> lys = Arrays.asList(lyIds.split(","));

        GzObj gzObj = new GzObj();
        gzObj.setId(Integer.parseInt(id));
        gzObj.setFilePath(filePath);
        gzObj.setName(name);
        gzObj.setBm(bm);
        gzObj.setDetailName(detailName);
        gzObj.setCfbm(cfbm);

        gzDao.deleteGzAndCs(id);
        for (int i = 0; i < bms.size(); i++) {
            gzDao.insertGzAndCs(id, css.get(i), bms.get(i), (lys.size() == 0 || lys.get(i).equals("undefined")) ? "0" : lys.get(i));
        }

        gzDao.modify(gzObj);
    }

    @Override
    public int selectOtherSameBmAndName(String id, String name, String bm) {
        // TODO Auto-generated method stub
        return gzDao.selectOtherSameBmAndName(id, name, bm);
    }

    @Override
    public void modifyGzzt(String ids, String gzzt) {
        // TODO Auto-generated method stub
        gzDao.modifyGzzt(Arrays.asList(ids.split(",")), gzzt);
    }

    @Override
    public RestServiceResult deleteGz(String id) {
        // TODO Auto-generated method stub
        String gzzt = gzDao.selectGzzt(id);
        if (gzzt.equals("Y")) {
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "规则状态未已发布，无法删除！");
        }

        gzDao.deleteGz(id, "Y");
        return new RestServiceResult(RestServiceResult.CODE_SUCCESS);
    }

    @Override
    public void download(String id, HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        GzObj gzObj = gzDao.selectById(id);
        String path = gzObj.getFilePath();
        FileUtil.uploadFile(path, request, response);
    }

    @Override
    public String checkDownload(String id) {
        // TODO Auto-generated method stub
        GzObj gzObj = gzDao.selectById(id);
        String path = gzObj.getFilePath();
        try {
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        }
        return "true";
    }

    @Override
    public void excelExport(HttpServletResponse response, String name, String bm, String gzzt, String type) {
        // TODO Auto-generated method stub
        queryTableExecle(response, name, bm, gzzt, type);
    }

    @Override
    public String getGzNames(String cfbm,String jclb) {
        return gzDao.getGzNames(cfbm,jclb);
    }

    @Override
    public GzObj selectByGzName(String gzName) {
        return gzDao.selectByGzName(gzName);
    }

    @Override
    public int selectCsIsExistByGzId(int gzId, String jclb, String type) {
        return gzDao.selectCsIsExistByGzId(gzId, jclb, type);
    }

    private void queryTableExecle(HttpServletResponse response, String name, String bm, String gzzt, String type) {
        // 生成提示信息
        response.setContentType("application/vnd.ms-excel");
        HSSFWorkbook workbook = null;
        OutputStream fOut = null;
        String codedFileName = "规则数据";
        // 进行转码，使其支持中文文件名
        try {
            codedFileName = URLEncoder.encode(codedFileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
        // 产生工作簿对象
        workbook = new HSSFWorkbook();
        // 产生工作表对象
        HSSFSheet sheet = workbook.createSheet();
        workbook.setSheetName(0, "具体备忘录数据");
        HSSFRow row = null;
        HSSFCell cell = null;

        String[] strBT = {"联合奖惩规则名称", "编码", "联合奖惩制度全称", "触发部门", "联合实施部门", "规则状态", "奖惩类别"};
        List<GzObj> list = gzDao.getListForAll(name, bm, gzzt, type);
        String ztType = "";

        //创建标题行
        row = sheet.createRow(0);
        for (int i = 0; i < strBT.length; i++) {
            cell = row.createCell(i);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(strBT[i]);
        }

        List<Map<String, Object>> lhbms = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < list.size(); i++) {
            int id = list.get(i).getId();
            lhbms = gzDao.selectForLhbm(id, bm, name);
            String lhbm = "";
            for (Map<String, Object> map : lhbms) {
                lhbm += map.get("deptName") + ",";
            }
            list.get(i).setLhbm(lhbm.substring(0, lhbm.length() - 1));

            row = sheet.createRow((int) i + 1);//创建一行
            cell = row.createCell(0);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(list.get(i).getName());

//	            row = sheet.createRow((int) i + 2);//创建一行
            cell = row.createCell(1);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(list.get(i).getBm());

//	            row = sheet.createRow((int) i + 3);//创建一行
            cell = row.createCell(2);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue((String) list.get(i).getDetailName());


//	            row = sheet.createRow((int) i + 4);//创建一行
            cell = row.createCell(3);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue((String) list.get(i).getCfbm());

            cell = row.createCell(4);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue((String) list.get(i).getLhbm());

            cell = row.createCell(5);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            String gzzt1 = list.get(i).getGzzt();
            if (gzzt1.equals("Y")) {
                type = "已发布";
            } else {
                type = "未发布";
            }
            cell.setCellValue(type);

            cell = row.createCell(6);
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            String jclb = list.get(i).getJclb();
            if (jclb.equals("C")) {
                type = "惩戒";
            } else {
                type = "激励";
            }

            cell.setCellValue(type);

        }
        list = null;
        try {
            fOut = response.getOutputStream();
            workbook.write(fOut);
            workbook.close();
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
